<template>
    <div class="home">
        <Show :details="details" :people="people" :showOrtab="showOrtab" @handleUpdate = "handleUpdate"/>
        <el-button class="showOrcss" @click="showOrtab = !showOrtab">{{showOrtab?'表格':'图片'}}</el-button>
        <el-button class="creacss" @click="handleCreate">新建纪念</el-button>
        <input id="file" class="importcss" type="file" accept=".json" v-if="!showOrtab"/>
        <el-button class="importcss" @click="importCreate" v-if="!showOrtab">导入</el-button>
        <el-button class="exportcss" @click="exportCreate" v-if="!showOrtab">导出</el-button>
        <el-button class="peoples" @click="peopleCreate">某人</el-button>
        <div class="peoples backscss" @click="backWay"></div>
        <div class="tabbox" v-if="!showOrtab">
            <el-table
                :data="details"
                border
                style="width: 100%">
                    <el-table-column
                    prop="startDate"
                    label="纪念日期"
                    align = "center"
                    width="300">
                    </el-table-column>
                    
                    <el-table-column
                    prop="img"
                    label="图片"
                    align = "center"
                    width="300">
                    </el-table-column>

                    <el-table-column
                    prop="tap"
                    label="标签"
                    align = "center"
                    width="180">
                    </el-table-column>

                    <el-table-column
                    prop="abouts"
                    label="详情"
                    min-width="500">
                    </el-table-column>

                    <el-table-column
                    fixed="right"
                    label="操作"
                    align = "center"
                    width="150">
                    <template slot-scope="scope">
                        <el-button @click="handleUpdate(scope.row)" type="primary" size="small">编辑</el-button>
                        <el-button @click="dletUpdate(scope.row)" size="small" type="danger">删除</el-button>
                    </template>
                    </el-table-column>
            </el-table>
        </div>
        <el-dialog :visible.sync="dialogFormVisible" :title="textMap[dialogStatus]" width="600px" top="70px">
            <el-form ref="dataForm" :rules="rules" :model="nodeModel" label-position="left" label-width="120px" style="width: 500px; margin-left:30px;">
                <el-form-item label="纪念日期" prop="startDate">
                    <el-date-picker v-model="nodeModel.startDate" value-format="yyyy-MM-dd" placeholder="开始日期" style="width: 100%;" />
                </el-form-item>
                <el-form-item label="活动名称" prop="tap">
                    <el-input v-model="nodeModel.tap"></el-input>
                </el-form-item>
                <el-form-item label="线上图片" prop="img">
                    <el-switch v-model="nodeModel.onLine" active-color="#13ce66" inactive-color="#ff4949">
                    </el-switch>
                </el-form-item>
                <el-form-item label="活动图片" prop="img">
                    <el-input v-model="nodeModel.img"></el-input>
                </el-form-item>
                <el-form-item label="活动详情" prop="abouts">
                    <el-input type="textarea" v-model="nodeModel.abouts" :autosize="{ minRows: 5}"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="dataOperation()">确定</el-button>
            </div>
        </el-dialog>
        <el-dialog :visible.sync="dialogPeopleVisible" title="某人" width="600px" top="138px">
            <el-form ref="peopleForm" :rules="rulesPeople" :model="people" label-position="left" label-width="120px" style="width: 500px; margin-left:30px;">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="people.name"></el-input>
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input v-model="people.age"></el-input>
                </el-form-item>
                <el-form-item label="生日" prop="birthday">
                    <el-input v-model="people.birthday"></el-input>
                </el-form-item>
                <el-form-item label="工作" prop="job">
                    <el-input v-model="people.job"></el-input>
                </el-form-item>
                <el-form-item label="线上图片" prop="img">
                    <el-switch v-model="people.onLine" active-color="#13ce66" inactive-color="#ff4949">
                    </el-switch>
                </el-form-item>
                <el-form-item label="图片" prop="img">
                    <el-input v-model="people.img"></el-input>
                </el-form-item>
                <el-form-item label="更多详情" prop="more">
                    <el-input type="textarea" v-model="people.more" :autosize="{ minRows: 5}"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogPeopleVisible = false">取消</el-button>
                <el-button type="primary" @click="dataOK()">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
// @ is an alias to /src
import Show from '@/components/show'
import FileSaver from 'file-saver';
export default {
    name: 'Home',
    components: {
        Show
    },
    data() {
        return {
            showOrtab:false,
            dialogFormVisible:false,
            textMap: {
                create: '创建纪念',
                update: '编辑纪念'
            },
            peopleIndex:0,
            nodeModel: {
                startDate: '',
                img: '',
                tap: '',
                onLine: false,
                abouts: ''
            },
            rules: {
                startDate: [
                    { required: true, message: '请选择开始日期', trigger: 'change' }
                ],
                abouts: [
                    { required: true, message: '请填写活动详情', trigger: 'blur' }
                ],
                tap: [
                    { required: true, message: '请填写活动名称', trigger: 'blur' }
                ],
                img: [
                    { required: true, message: '请填写活动图片', trigger: 'blur' }
                ]
            },
            dialogStatus: 'create',
            people:{
                name:'李思云',
                age:27,
                birthday:'1月15日',
                job:'策展人',
                onLine: false,
                img:'QRBHS.jpg',
                more:'怕高，怕小动物，不爱看电影，不爱听歌，不打游戏'
            },
            dialogPeopleVisible:false,
            rulesPeople: {
                name: [
                    { required: true, message: '请填写名称', trigger: 'blur' }
                ],
                age: [
                    { required: true, message: '请填写年龄', trigger: 'blur' }
                ],
                birthday: [
                    { required: true, message: '请填写生日', trigger: 'blur' }
                ],
                job: [
                    { required: true, message: '请填写工作', trigger: 'blur' }
                ],
                img: [
                    { required: true, message: '请填写图片', trigger: 'blur' }
                ],
                more: [
                    { required: true, message: '请填写更多', trigger: 'blur' }
                ]
            },
            details: [
                {
                    img:"photoWall1",
                    onLine:false,
                    startDate:'2024-1-2',
                    tap:'趣味相投的知音',
                    abouts:'一个画展逛下来，她的品味跟我差不多，我说的笑话她也能get到，真是知音呐 ! 相见恨晚，相见恨晚。'
                },
                {
                    img:"photoWall1",
                    onLine:false,
                    startDate:'2024-1-2',
                    tap:'西伯利亚土拨鼠',
                    abouts:'居然是她 ! 那个陪我度过漫漫长夜的网友，那个在列表里灰了很久的头像，竟然在现实生活中相遇了 。缘，真是妙不可言。'
                },
                {
                    img:"photoWall1",
                    onLine:false,
                    startDate:'2024-1-2',
                    tap:'理想家',
                    abouts:'她对我放弃画画的决定很失望，可我觉得是她活得太过理想。'
                },
                {
                    img:"photoWall1",
                    onLine:false,
                    startDate:'2024-1-2',
                    tap:'大大大大恩人',
                    abouts:'兜兜转转，还是她收容了开店失败的我。救助之恩，无以为报，唯有......努力赚钱 !'
                },
                {
                    img:"photoWall1",
                    onLine:false,
                    startDate:'2024-1-2',
                    tap:'人生赢家',
                    abouts:'她跟那个男人看起来很般配。她美丽优雅、事业成功、将来也会家庭幸福......完蛋，好像只要我不在，她的生活就很完美。'
                },
                {
                    img:"photoWall1",
                    onLine:false,
                    startDate:'2024-1-2',
                    tap:'留鸟',
                    abouts:'蓦然回首，她还守在灯火阑珊处 。'
                },
            ]
        }
    },
    mounted() {
    },
    created(){
        this.ref()
    },
    beforeDestroy() {
        let humanList = localStorage.getItem("human");
        if (humanList) {
            let human = JSON.parse(humanList);
            if(human.length){
                this.peopleIndex = human.findIndex(item => item.people.name==this.people.name)
                if(this.peopleIndex>=0){
                    human[this.peopleIndex].people = this.people
                    human[this.peopleIndex].details = this.details
                }else{
                    human.push({people:this.people,details:this.details})
                }
                localStorage.setItem("human", JSON.stringify(human));
            }
        }else{
            humanList = []
            humanList.push({people:this.people,details:this.details})
            localStorage.setItem("human", JSON.stringify(humanList));
        }
    },
    methods: {
        resetModel() {
            this.nodeModel = {
                startDate: '',
                img: '',
                tap: '',
                onLine: false,
                abouts: ''
            }
        },
        // 创建
        handleCreate() {
            this.resetModel()
            this.dialogStatus = 'create'
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        // 编辑
        handleUpdate(row) {
            this.resetModel()
            this.dialogStatus = 'update'
            this.dialogFormVisible = true
            this.nodeModel = row
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        // 确认
        dataOperation() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    if (this.dialogStatus === 'create') {
                        this.details.push(this.nodeModel)
                        this.operationRes()
                    }
                    if (this.dialogStatus === 'update') {
                        this.operationRes()
                    }
                }
            })
        },
        // 修改个人信息
        dataOK() {
            this.$refs['peopleForm'].validate((valid) => {
                if (valid) {
                    this.dialogPeopleVisible = false
                    localStorage.setItem("people", JSON.stringify(this.people));
                    this.$message({
                    message: '修改成功',
                    type: 'success'
                    })
                }
            })
        },
        operationRes() {
            this.dialogFormVisible = false
            localStorage.setItem("details", JSON.stringify(this.details));
            this.$message({
            message: this.textMap[this.dialogStatus] + '成功',
            type: 'success'
            })
        },
        // 删除
        dletUpdate(i){
            let index = this.details.findIndex(item => item === i)
            this.details.splice(index, 1);
            localStorage.setItem("details", JSON.stringify(this.details));
            this.$message({
                message:'删除成功',
                type: 'success'
            })
        },
        // 打开个人信息
        peopleCreate(){
            this.dialogPeopleVisible = true;
        },
        // 导入数据
        importCreate(){
            const file = document.getElementById('file').files[0];
            if(file){
                console.log('导入成功')
                const reader = new FileReader();
                reader.readAsText(file);
                let that = this
                reader.onload = function() {
                    // this.result为读取到的json字符串，需转成json对象
                    let originlist = JSON.parse(this.result);
                    that.people=originlist.people
                    that.details=originlist.details
                    localStorage.setItem("people", JSON.stringify(that.people));
                    localStorage.setItem("details", JSON.stringify(that.details));
                    // 检测是否导入成功
                    console.log(originlist.value);
                };
            }else{
                console.log('导入失败')
                this.$message({
                    message:'导入失败: 请上传文件！！！',
                    type: 'info'
                })
            }
        },
        // 导出数据
        exportCreate(){
            // 将json转换成字符串
            const data = JSON.stringify({people:this.people,details:this.details});
            const blob = new Blob([data], { type: '' });
            FileSaver.saveAs(blob, 'mylife.json');
        },
        backWay(){
            this.$router.push({
                path: "/about"
            })
        },
        ref(){
            // let details = localStorage.getItem("details");
            // if (details) {
            //     this.details = JSON.parse(details);
            // }
            // let people = localStorage.getItem("people");
            // if (people) {
            //     this.people = JSON.parse(people);
            // }
            let humanList = localStorage.getItem("human");
            if (humanList) {
                let human = JSON.parse(humanList);
                if(human.length){
                    console.log('this.$router.query.peopleName',this.$route)
                    if(this.$route.query.peopleName){
                        this.peopleIndex = human.findIndex(item => item.people.name==this.$route.query.peopleName)
                        if(this.peopleIndex>=0){
                            this.people = human[this.peopleIndex].people
                            this.details = human[this.peopleIndex].details
                        }else{
                            this.people = {
                                name:this.$route.query.peopleName,
                                age:'',
                                birthday:'',
                                job:'',
                                onLine: false,
                                img:'test1.jpeg',
                                more:''
                            }
                            this.details = []
                        }
                    }else{
                        this.people = human[this.peopleIndex].people
                        this.details = human[this.peopleIndex].details
                    }
                }
            }
        }
    }
}
</script>
<style lang="scss" scoped>

.home{
    display: flex;
}
.tabbox{
    width: calc(100% - 320px);
    position: relative;
    left: 0;
    min-height: 100vh;
    box-sizing: border-box;
    padding-top: 100px;
    
}

.showOrcss{
    position: fixed;
    right: 40px;
    top: 30px;
    z-index: 9;
}
.creacss{
    position: fixed;
    right: 140px;
    top: 30px;
    z-index: 9;
}
#file{
    width: 170px;
    right: 430px;
    top: 38px;
    background-color: #fff;
}
.importcss{
    position: fixed;
    right: 340px;
    top: 30px;
    z-index: 3;
}
.exportcss{
    position: fixed;
    right: 255px;
    top: 30px;
    z-index: 9;
}
.peoples{
    position: fixed;
    left: 220px;
    top: 30px;
    z-index: 3;
}
.backscss{
    left: 20px;
    top: 25px;
    background-image: url(../assets/images/back.png);
    background-size: 100% 100%;
    width: 54px;
    height: 54px;
    cursor: pointer;
}
</style>


